<template>
  <div class="home">
    <div v-if="true"
         class="location display-row-center">
      <p class="font-size-14 location-p div-over-width">{{ location_text }}</p>
      <van-image class="location-img"
                 :class="{ 'location-img-rotate': location_flag }"
                 fit="contain"
                 :src="require('@/assets/icon/shuaxin@3x.png')"
                 @click="getCurrentLocation" />
    </div>
    <div class="search-around display">
      <img src="../assets/icon/touxiang@3x.png"
           class="search-avatar"
           @click="handleGoMyPage" />
      <search-input class="search-component"
                    :placeholder_value="'景区/文博场馆/民宿/餐馆'"></search-input>
    </div>
    <div class="swiper">
      <carousel-3d autoplay
                   :autoplay-timeout="3000"
                   class="swiper-item"
                   v-if="carousel_list.length !== 0">
        <slide :index="index"
               v-for="(item, index) of carousel_list"
               :key="item.id">
          <van-image width="100%"
                     style="object-fit: cover;"
                     :src="item.img"
                     @click="getSwiperImg(item)" />
        </slide>
      </carousel-3d>
    </div>
    <div class="type-around">
      <div class="display-col">
        <div class="display news-around">
          <img src="@/assets/image/zixun@2x.png"
               class="news-img" />
          <div class="font-size-16 news-content width-65 div-over-width"
               @click="goNews">
            {{ index_data.sys_news && index_data.sys_news.length !== 0 ? index_data.sys_news[0].title : '暂无资讯' }}
          </div>
        </div>
        <div class="display width-100"
             style="margin: 0.483092rem 0.700483rem">
          <div v-for="(item, index) of typeList"
               :key="index"
               class="display-col"
               @click="handleGoDetails(index)">
            <img :src="item.img"
                 class="img-40" />
            <div class="font-size-12">{{ item.name }}</div>
          </div>
        </div>
      </div>
    </div>
    <modeTitle :title="typeList.length !== 0 ? typeList[1].name : ''"
               :module_name="1" />
    <div class="action-around"
         v-if="tickets_list.length > 0">
      <van-grid :border="false"
                :column-num="2"
                class="action-around-item">
        <van-grid-item v-for="(item, index) in tickets_list"
                       :key="index"
                       @click="handleGoTicketPage(item)">
          <template #icon>
            <img :src="item.img"
                 class="fire-swiper-img" />
          </template>
          <template #text>
            <div class="display-col fire-swiper-content">
              <div class="font-size-16 font-color-3D444D"
                   style="padding-bottom: 0.217391rem">{{ item.name }}</div>
              <div class="fire-pay">
                <p class="font-size-14">￥</p>
                <p class="font-size-20 font-weight-500">{{ item.sku_min_price || 0 }}</p>
                <p class="font-size-12">&nbsp;起</p>
              </div>
            </div>
          </template>
        </van-grid-item>
      </van-grid>
    </div>
    <van-empty v-else
               class="custom-image"
               image="https://img01.yzcdn.cn/vant/custom-empty-image.png"
               description="暂无热销门票" />
    <modeTitle :title="typeList.length !== 0 ? typeList[2].name : ''"
               :module_name="2" />
    <div class="home-list-home"
         v-if="hotel_list.length != 0">
      <imageTitle v-if="hotel_list.length > 0"
                  :title="hotel_list? hotel_list[0].name : ''"
                  :image-url="hotelImg(0)"
                  :content="hotel_list ? `${hotel_list[0].shop?hotel_list[0].shop.name + ',':''}距我${hotel_list[0].distance?hotel_list[0].distance.distance.toFixed(0):0}Km` : ''"
                  :size="true"
                  class="home-img-title"
                  @click.native="handleGoTicketPage(hotel_list[0])" />
      <div class="display-col home-img-title-right"
           style="height: 100%">
        <imageTitle v-if="hotel_list.length > 1"
                    :title="hotel_list ? hotel_list[1].name : ''"
                    :image-url="hotelImg(1)"
                    class="home-img-title-right__content"
                    :style="{'margin-bottom': hotel_list.length > 2 ?'0.289855rem':'0rem' }"
                    @click.native="handleGoTicketPage(hotel_list[1])" />
        <imageTitle v-if="hotel_list.length > 2"
                    :title="hotel_list ? hotel_list[2].name : ''"
                    :image-url="hotelImg(2)"
                    class="home-img-title-right__content"
                    @click.native="handleGoTicketPage(hotel_list[2])" />
      </div>
    </div>
    <van-empty v-else
               class="custom-image"
               image="https://img01.yzcdn.cn/vant/custom-empty-image.png"
               description="暂无优选住宿" />
    <modeTitle :title="typeList.length !== 0 ? typeList[3].name : ''"
               :module_name="3" />
    <div class="display food-list"
         v-if="food_list.length > 0">
      <div class="display-col food-card"
           v-for="(item, index) in food_list"
           :key="index"
           @click.stop="handleGoShopgetById(item.id)">
        <img :src="item.img"
             class="food-img" />
        <div class="food-page">
          <div class="font-size-16 font-weight-500 font-color-3D444D">{{ item.name }}</div>
          <div class="font-size-12 font-color-8C9198"
               v-if="item.distance"><span v-if="item.shop">{{ item.shop.name }},</span> 距我{{item.distance.distance.toFixed(0)}}km</div>
          <momenyTitle :number=" item.sku_min_price " />
        </div>
      </div>
    </div>
    <van-empty v-else
               class="custom-image"
               image="https://img01.yzcdn.cn/vant/custom-empty-image.png"
               description="暂无热门美食" />
    <modeTitle :title="typeList.length !== 0 ? typeList[4].name : ''"
               :module_name="4" />
    <div class="home-list display"
         v-if="specialty_list.length > 0"
         :style="{ height: specialty_list.length > 1 ? '3.864734rem' : '1.78744rem' }">
      <van-grid direction="horizontal"
                :border="false"
                :column-num="2"
                class="home-list-item">
        <van-grid-item v-for="(item, index) of specialty_list"
                       :key="index"
                       @click.stop="handleGoShopgetById(item.id)">
          <template #icon>
            <van-image class="home-list-item-img"
                       fit="cover"
                       :src="item.img" />
          </template>
          <template #text>
            <div class="home-list-item-text">
              <div class="font-size-16 div-over-width font-color-3D444D">{{ item.name }}</div>
              <div class="font-size-14 font-color-8C9198"
                   v-if="item.shop">{{ item.shop.name }}</div>
            </div>
          </template>
        </van-grid-item>
      </van-grid>
    </div>
    <van-empty v-else
               class="custom-image"
               image="https://img01.yzcdn.cn/vant/custom-empty-image.png"
               description="暂无优选特产" />
    <div class="list-end font-size-14 padding-30"
         @click="$router.push({ path: '/detailsPage', query: { module_name: '1' } })">附近更多好玩景点推荐</div>
  </div>
</template>
<script type="text/javascript" src=""></script>
<script>
import { Toast } from 'vant';
import SearchInput from '@/components/SearchInput';
import modeTitle from '@/components/modeTitle';
import imageTitle from '@/components/imageTitle';
import momenyTitle from '@/components/momenyTitle';
import { Carousel3d, Slide } from 'vue-carousel-3d';
import cookie from '@/utils/cookie';
export default {
  components: {
    SearchInput,
    modeTitle,
    imageTitle,
    momenyTitle,
    Carousel3d,
    Slide,
  },
  name: 'index',
  data () {
    return {
      location_flag: false, //获取定位标识
      location_text: '定位获取失败，重新获取定位', //位置信息
      index_data: {}, //首页数据
      carousel_list: [], //轮播图列表
      typeList: [], //金刚区导航
      default_typelist_img: [
        require('@/assets/image/jingdian@3x.png'),
        require('@/assets/image/menpiao@3x.png'),
        require('@/assets/image/jiudian@3x.png'),
        require('@/assets/image/meishi@3x.png'),
        require('@/assets/image/techan@3x.png'),
      ], //默认金刚区图片
      tickets_list: [], //门票列表
      hotel_list: [], //住宿列表
      food_list: [], //美食列表
      specialty_list: [], //特产列表
      searchWord: '', // 搜索
    };
  },
  mounted () {
    //存储 乡镇id
    if (this.$route.query.town_id) {
      cookie.set('town_id', this.$route.query.town_id);
    }
    this.location_flag = true;
    this.loadScript('https://webapi.amap.com/maps?v=1.4.15&key=c8ba837d982c156d8e3597e6c021fe90', () => {
      this.getLocationFn();
    });
    this.getIndexAll();
  },
  methods: {
    hotelImg (index) {
      //优选住宿图片
      return this.hotel_list ? this.hotel_list[index].img : '';
    },
    getIndexAll () {
      //获取首页聚合接口
      _api
        .api_userPortal_home({
          town_id: this.$route.query.town_id || 14,
        })
        .then((res) => {
          this.index_data = res.data;
          if (this.index_data.sys_banners.length !== 0) {
            this.carousel_list = [];
            this.carousel_list = this.index_data.sys_banners;
          } else {
            this.carousel_list = [
              {
                id: 1,
                img: require('@/assets/image/banner@3x.png'),
              },
            ];
          }
          this.food_list = this.index_data.tour_product_foods;
          this.specialty_list = this.index_data.tour_product_specialties;
          this.typeList = this.index_data.sys_navigations.reverse();
          this.typeList.map((res, index) => {
            if (!res.img) {
              res.img = this.default_typelist_img[index];
            }
          });
          localStorage.setItem('NavList', JSON.stringify(this.typeList));
          this.tickets_list = this.index_data.tour_product_tickets;
          this.hotel_list = this.index_data.tour_product_hotels;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    getSwiperImg (info) {
      //轮播点击
      if (Number(info.target_type) === 2) {
        location.href = `http://${info.target}`;
      }
      if (Number(info.target_type) === 1) {
        this.handleGoShopgetById(info.target);
      }
    },
    getCurrentLocation () {
      if (!this.location_flag) {
        this.location_flag = true;
        this.getLocationFn();
      }
    },
    handleGoMyPage () {
      this.$router.push('/my');
    },
    handleGoTicketPage (e) {
      console.log(JSON.stringify(e));
      this.$router.push({ path: '/masterPage', query: { id: e.id, shop_id: e.shop_id, type: e.type } });
    },
    handleGoHome () {
      this.$router.push({ path: '/masterPage', query: { card_id: 2, module_name: '2' } });
    },
    handleGoFoodPage () {
      this.$router.push({ path: '/masterPage', query: { card_id: 3, module_name: '3' } });
    },
    handleGoSpecialtyPage () {
      this.$router.push({ path: '/masterPage', query: { card_id: 4, module_name: '4' } });
    },
    // 商品详情页
    handleGoShopgetById (id) {
      this.$router.push({ path: '/check', query: { tour_product_id: id } });
    },
    handleGoDetails (index) {
      //去详情页
      switch (index) {
        case 0:
        case 1:
        case 2:
        case 3:
        case 4:
          this.$router.push({ path: '/detailsPage', query: { module_name: index.toString() } });
          break;
        default:
          console.log(index);
      }
    },
    goNews () {
      //去往最新资讯
      this.$router.push('/News');
    },
    //判断JS是否加载完成
    loadScript (url, callback) {
      //循环清除所以的类
      for (var i = 0; i < document.querySelectorAll('.script_class').length; i++) {
        document
          .querySelectorAll('.script_class')
        [i].parentNode.removeChild(document.querySelectorAll('.script_class')[i]);
      }
      var script = document.createElement('script');
      script.type = 'text/javascript';
      script.async = 'async';
      script.src = url;
      script.setAttribute('class', 'script_class');
      document.body.appendChild(script);

      if (script.readyState) {
        //IE
        script.onreadystatechange = function (e) {
          if (script.readyState == 'complete' || script.readyState == 'loaded') {
            script.onreadystatechange = null;
            callback();
          }
        };
      } else {
        //非IE
        script.onload = function (e) {
          //加载完成执行回调
          callback();
        };
      }
    },
    getLocationFn () {
      AMap.plugin('AMap.Geolocation', () => {
        var geolocation = new AMap.Geolocation({
          // 是否使用高精度定位，默认：true
          enableHighAccuracy: true,
        });
        geolocation.getCurrentPosition();
        AMap.event.addListener(geolocation, 'complete', onComplete);
        AMap.event.addListener(geolocation, 'error', onError);
        let self = this;
        function onComplete (data) {
          self.location_text = data.formattedAddress;
          self.location_flag = false;
          const item_obj = { ...data.position, formattedAddress: data.formattedAddress };
          cookie.set('location', JSON.stringify(item_obj));
          console.log(JSON.stringify(data));
          //获取首页聚合接口
          _api
            .api_userPortal_home({
              town_id: self.$route.query.town_id || 14,
              lon: data.position.lng,
              lat: data.position.lat,
            })
            .then((res) => {
              self.food_list = res.data.tour_product_foods;
              self.hotel_list = res.data.tour_product_hotels;
            })
            .catch((error) => {
              console.log(error);
            });
        }
        function onError (data) {
          console.log(data);
          self.location_text = '定位获取失败，重新获取定位';
          self.location_flag = false;
          cookie.remove('location');

          if (data.message === 'Geolocation permission denied.') {
            Toast('请手动清除浏览器缓存或者设置app开启浏览器定位功能');
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import 'index.scss';
input:-moz-placeholder {
	/* Mozilla Firefox 4 to 18 */
	color: #ffffff;
	opacity: 1;
}
body::-webkit-scrollbar {
	display: none;
}
input::-moz-placeholder {
	/* Mozilla Firefox 19+ */
	color: #ffffff;
	opacity: 1;
}
input:-ms-input-placeholder {
	color: #ffffff;
	opacity: 1;
}
input::-webkit-input-placeholder {
	color: #ffffff;
	opacity: 1;
}
</style>
